<template>
  <view class="container">
    <!-- Status bar placeholder -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- Top navigation bar -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="navbar-title">我的订单</view>
      <view class="navbar-right"></view>
    </view>
    
    <!-- Order status tabs -->
    <view class="order-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        class="tab-item" 
        :class="{ active: currentTab === index }"
        @click="switchTab(index)"
      >
        <text>{{ tab.name }}</text>
      </view>
    </view>
    
    <!-- Order list -->
    <scroll-view 
      class="order-list" 
      scroll-y 
      @scrolltolower="loadMoreOrders"
      :style="{ height: scrollViewHeight + 'px' }"
    >
      <!-- Loading indicator -->
      <view v-if="loading && !orders.length" class="loading-container">
        <uni-icons type="spinner-cycle" size="30" color="#FF8C42"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- Empty order prompt -->
      <view v-else-if="!loading && !orders.length" class="empty-container">
        <image class="empty-image" src="/static/empty-order.png" mode="aspectFit"></image>
        <text class="empty-text">暂无订单</text>
        <button class="go-shopping-btn" @click="goShopping">去购物</button>
      </view>
      
      <!-- Order list content -->
      <view v-else>
        <view 
          v-for="order in orders" 
          :key="order.id" 
          class="order-item"
          @click="viewOrderDetail(order.orderNo)"
        >
          <view class="order-header">
            <view class="order-no">订单号: {{ order.orderNo }}</view>
            <view class="order-status">{{ getStatusText(order.status) }}</view>
          </view>
          
          <view class="order-content">
            <!-- Order product preview -->
            <view class="order-products" v-if="order.orderItems && order.orderItems.length > 0">
              <view class="product-preview" v-for="(item, index) in order.orderItems.slice(0, 3)" :key="index">
                <image class="product-image" :src="imageFullUrl(item.productImage)" mode="aspectFill"></image>
              </view>
              <view class="product-count" v-if="order.orderItems.length > 3">
                <text>共{{ order.orderItems.length }}件</text>
              </view>
            </view>
            
            <!-- Order summary info -->
            <view class="order-summary">
              <text class="order-time">下单时间: {{ formatDate(order.createTime) }}</text>
              <text class="order-amount">总金额: ¥{{ order.totalAmount }}</text>
            </view>
          </view>
          
          <view class="order-footer">
            <!-- Different action buttons based on order status -->
            <!-- <template v-if="order.status === 0">
              <button class="order-btn cancel-btn" @click.stop="cancelOrder(order.orderNo)">取消订单</button>
              <button class="order-btn primary-btn" @click.stop="payOrder(order.orderNo, order.totalAmount)">去支付</button>
            </template> -->
            <template v-if="order.status === 1">
              <button class="order-btn primary-btn" @click.stop="reorderItems(order.orderNo)">再来一单</button>
            </template>
            <template v-else-if="order.status === 2">
              <button class="order-btn primary-btn" @click.stop="confirmReceipt(order.orderNo)">确认收货</button>
            </template>
            <template v-else-if="order.status === 3">
              <button class="order-btn" @click.stop="viewOrderDetail(order.orderNo)">查看详情</button>
              <button class="order-btn primary-btn" @click.stop="rateOrder(order.orderNo)">评价订单</button>
            </template>
          </view>
        </view>
        
        <!-- Load more indicator -->
        <view v-if="loading && orders.length" class="loading-more">
          <uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
          <text>加载更多...</text>
        </view>
        
        <!-- No more data prompt -->
        <view v-if="!loading && !hasMore && orders.length" class="no-more">
          <text>没有更多订单了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { useCartStore } from '@/store/cart';
import { useOrderStore } from '@/store/order';
import http from '@/utils/http/http.js';
import { getImageUrl } from '@/config/env';

const userStore = useUserStore();
const cartStore = useCartStore();
const orderStore = useOrderStore();
const statusBarHeight = ref(0);
const scrollViewHeight = ref(0);

// Order status tabs
const tabs = [
  { name: '全部', status: null },
  { name: '已完成', status: 0 },
  { name: '待发货', status: 1 },
  { name: '待收货', status: 2 },
  { name: '已完成', status: 3 }
];

const currentTab = ref(0);
const orders = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);

// Generate full image URL
const imageFullUrl = (path) => {
  if (!path) return '/static/placeholder.png';
  return getImageUrl(path);
};

// Get status bar height and calculate scroll view height
const getSystemInfo = () => {
  try {
    if (typeof uni !== 'undefined') {
      const systemInfo = uni.getSystemInfoSync();
      statusBarHeight.value = systemInfo.statusBarHeight || 0;
      
      // Calculate scroll view height = screen height - status bar height - navbar height(44px) - tab height(44px) - bottom safe area(20px)
      scrollViewHeight.value = systemInfo.windowHeight - statusBarHeight.value - 44 - 44 - 20;
    } else {
      statusBarHeight.value = 0;
      scrollViewHeight.value = 500; // Default height
    }
  } catch (e) {
    console.error('Failed to get system info:', e);
    statusBarHeight.value = 0;
    scrollViewHeight.value = 500; // Default height
  }
};

// Go back to previous page
const goBack = () => {
  uni.navigateBack();
};

// Switch tab
const switchTab = (index) => {
  if (currentTab.value === index) return;
  
  currentTab.value = index;
  // Reset pagination and data
  currentPage.value = 1;
  orders.value = [];
  hasMore.value = true;
  
  // Reload data
  loadOrders();
};

// Load order data
const loadOrders = async () => {
  if (loading.value || !hasMore.value) return;
  
  loading.value = true;
  
  try {
    // Check login status
    if (!userStore.isLoggedIn || !userStore.token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      uni.navigateBack();
      return;
    }
    
    // Build request parameters
    let url = `/api/orders/list?pageNum=${currentPage.value}&pageSize=${pageSize.value}`;
    
    // If not "All" tab, add status filter
    if (tabs[currentTab.value].status !== null) {
      url += `&status=${tabs[currentTab.value].status}`;
    }
    
    // Send request
    const response = await http.get(url, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data) {
      const newOrders = response.data.list || [];
      
      // Append data
      if (currentPage.value === 1) {
        orders.value = newOrders;
      } else {
        orders.value = [...orders.value, ...newOrders];
      }
      
      // Check if there's more data
      hasMore.value = newOrders.length === pageSize.value;
      
      // Update page number
      if (hasMore.value) {
        currentPage.value++;
      }
      
      // Get details for each order to display product images
      for (const order of newOrders) {
        fetchOrderItems(order.orderNo);
      }
    } else {
      uni.showToast({
        title: response.message || '获取订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('Failed to load orders:', error);
    uni.showToast({
      title: '加载订单失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// Get order items
const fetchOrderItems = async (orderNo) => {
  try {
    const response = await http.get(`/api/orders/detail/${orderNo}`, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data) {
      // Find the corresponding order and add items
      const index = orders.value.findIndex(order => order.orderNo === orderNo);
      if (index !== -1) {
        orders.value[index].orderItems = response.data.orderItems || [];
      }
    }
  } catch (error) {
    console.error(`Failed to get items for order ${orderNo}:`, error);
  }
};

// Load more orders
const loadMoreOrders = () => {
  if (hasMore.value && !loading.value) {
    loadOrders();
  }
};

// View order details
const viewOrderDetail = (orderNo) => {
  uni.navigateTo({
    url: `/pages/orders/order-detail?orderNo=${orderNo}`
  });
};

// Cancel order
const cancelOrder = async (orderNo) => {
  uni.showModal({
    title: '提示',
    content: '确定要取消该订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await http.post(`/api/orders/cancel/${orderNo}`, {}, {
            header: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // Reload current page data
            currentPage.value = 1;
            orders.value = [];
            hasMore.value = true;
            loadOrders();
          } else {
            uni.showToast({
              title: response.message || '取消订单失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('Failed to cancel order:', error);
          uni.showToast({
            title: '取消订单失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// Pay for order
const payOrder = (orderNo, amount) => {
  uni.navigateTo({
    url: `/pages/orders/payment?orderNo=${orderNo}&amount=${amount}`
  });
};

// Reorder items (new implementation)
const reorderItems = async (orderNo) => {
  try {
    uni.showLoading({
      title: '处理中...'
    });
    
    // Get order details
    const orderDetail = await orderStore.fetchOrderDetail(orderNo);
    
    if (!orderDetail || !orderDetail.orderItems || orderDetail.orderItems.length === 0) {
      uni.showToast({
        title: '订单商品信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // Clear cart first (optional, based on business requirements)
    // await cartStore.clearCart();
    
    // Add each item to cart
    let addedCount = 0;
    for (const item of orderDetail.orderItems) {
      // Create product object from order item
      const product = {
        id: item.productId,
        name: item.productName,
        price: item.unitPrice,
        mainImageUrl: item.productImage,
        status: 1, // Assume product is available
        totalStock: 999, // Assume sufficient stock
        spec: item.productSpec || ''
      };
      
      // Add to cart
      const success = await cartStore.addToCart(product, item.quantity);
      if (success) {
        addedCount++;
      }
    }
    
    uni.hideLoading();
    
    if (addedCount > 0) {
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
      
      // Navigate to cart page
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/cart/index'
        });
      }, 1500);
    } else {
      uni.showToast({
        title: '添加商品失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('再来一单失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// Confirm receipt
const confirmReceipt = async (orderNo) => {
  uni.showModal({
    title: '提示',
    content: '确认已收到商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await http.post(`/api/orders/confirm/${orderNo}`, {}, {
            header: {
              'Authorization': `Bearer ${userStore.token}`
            }
          });
          
          if (response.code === 200) {
            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            });
            
            // Reload current page data
            currentPage.value = 1;
            orders.value = [];
            hasMore.value = true;
            loadOrders();
          } else {
            uni.showToast({
              title: response.message || '确认收货失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('Failed to confirm receipt:', error);
          uni.showToast({
            title: '确认收货失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// Rate order
const rateOrder = (orderNo) => {
  uni.navigateTo({
    url: `/pages/orders/rate?orderNo=${orderNo}`
  });
};

// Go shopping
const goShopping = () => {
  uni.redirectTo({
    url: '/pages/index/index'
  });
};

// Get order status text
const getStatusText = (status) => {
  switch (status) {
    case 0: return '已完成';
    case 1: return '待发货';
    case 2: return '待收货';
    case 3: return '已完成';
    case 4: return '已取消';
    default: return '未知状态';
  }
};

// Format date
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// Execute on page load
onMounted(() => {
  if (typeof uni !== 'undefined') {
    console.log('Order list page loaded');
    getSystemInfo();
    loadOrders();
  } else {
    console.warn('uni is not defined. This might be running in an environment where uni is not available.');
  }
});
</script>

<style>
.container {
  background-color: #FFF9F2;
  min-height: 100vh;
}

.navbar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 0 15px;
}

.navbar-left {
  width: 40px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.navbar-right {
  width: 40px;
}

.order-tabs {
  display: flex;
  background-color: #fff;
  height: 44px;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #FF8C42;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background-color: #FF8C42;
  border-radius: 2px;
}

.order-list {
  background-color: #FFF9F2;
  padding: 10px;
}

.loading-container, .empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 50px 0;
}

.loading-text, .empty-text {
  margin-top: 10px;
  font-size: 14px;
  color: #999;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.go-shopping-btn {
  margin-top: 20px;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  padding: 5px 20px;
}

.order-item {
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-bottom: 1px solid #f5f5f5;
}

.order-no {
  font-size: 13px;
  color: #666;
}

.order-status {
  font-size: 13px;
  color: #FF8C42;
  font-weight: bold;
}

.order-content {
  padding: 15px;
}

/* Order product preview */
.order-products {
  display: flex;
  margin-bottom: 15px;
}

.product-preview {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  border-radius: 5px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.product-count {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
}

.order-amount {
  font-weight: bold;
  color: #333;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 15px;
  border-top: 1px solid #f5f5f5;
  gap: 10px;
}

.order-btn {
  font-size: 12px;
  padding: 5px 12px;
  border-radius: 15px;
  background-color: #fff;
  color: #666;
  border: 1px solid #ddd;
  line-height: 1.5;
}

.primary-btn {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  border: none;
}

.cancel-btn {
  border: 1px solid #FF8C42;
  color: #FF8C42;
  background-color: #fff;
}

.loading-more, .no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px 0;
  font-size: 12px;
  color: #999;
}

.loading-more uni-icons {
  margin-right: 5px;
}
</style>